//
//  SearchNewsController.m
//  kr_36
//
//  Created by lmt on 16/1/27.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SearchNewsController.h"
#import "AllTableViewCell.h"
#import "AllModel.h"
#import "LMTAFNetwork.h"
#import <UIImageView+WebCache.h>
#import "LMTTImeChuo.h"
#import "NewsDetailViewController.h"
#import <MJRefresh.h>

@interface SearchNewsController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataArr;

@property (nonatomic, assign) NSInteger i;
@property (nonatomic, retain) UILabel *total;

@end

@implementation SearchNewsController

- (void)dealloc
{
    [_tableView release];
    [_dataArr release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    self.navigationItem.title = [NSString stringWithFormat:@"搜新闻资讯:%@", _str];
    
    // 创建tableView
    [self createTableView];
    
    // 数据解析
    [self dataHander];
    
    _i = 2;
    
    // 上拉加载
    [self loading];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    
    self.total = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, view.frame.size.width, 28)];
    [view addSubview:_total];
    
    UIView *xian = [[UIView alloc] initWithFrame:CGRectMake(0, 28, view.frame.size.width, 2)];
    xian.backgroundColor = [UIColor cyanColor];
    xian.alpha = 0.6;
    [view addSubview:xian];
    
    
    
    _tableView.tableHeaderView = view;
    [xian release];
    [_total release];
    [view release];
}

- (void)loading
{
    
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        //延迟两秒
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            NSString *str = [NSString stringWithFormat:@"https://rong.36kr.com/api/mobi/news/search?keyword=%@&page=%ld&pageSize=20", _str, _i];
            [LMTAFNetwork getUrl:str body:nil response:LMTJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
               
                NSMutableArray *arr = resposeObject[@"data"][@"data"];
                NSMutableArray *temp = [AllModel modelHanderWithArray:arr];
                
                for (AllModel *m in temp) {
                    [self.dataArr addObject:m];
                }
                
                [_tableView reloadData];
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
            }];
            _i++;
            [_tableView.mj_footer endRefreshing];
        });
    }];
    _tableView.mj_footer = footer;
}


- (void)dataHander
{
    NSString *str = [NSString stringWithFormat:@"https://rong.36kr.com/api/mobi/news/search?keyword=%@&page=1&pageSize=20", _str];
    [LMTAFNetwork getUrl:str body:nil response:LMTJSON requestHeadFile:nil success:^(NSURLSessionDataTask *task, id resposeObject) {
        
        NSNumber *total = resposeObject[@"data"][@"totalCount"];
        _total.text = [NSString stringWithFormat:@"共搜索到%@条结果", total];
        
        NSMutableArray *arr = resposeObject[@"data"][@"data"];
        self.dataArr = [AllModel modelHanderWithArray:arr];
        [_tableView reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStylePlain)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView release];
    [_tableView registerClass:[AllTableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AllTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    AllModel *m = _dataArr[indexPath.row];
    
    ///高亮设置
    NSMutableAttributedString *attrituteString = [[NSMutableAttributedString alloc] initWithString:m.title];
    NSRange range = [m.title rangeOfString:_str];
    [attrituteString setAttributes:@{NSForegroundColorAttributeName : [UIColor redColor],   NSFontAttributeName : [UIFont systemFontOfSize:18]} range:range];
    
    cell.title.attributedText = attrituteString;
    cell.columName.text = m.columnName;
    cell.name.text = m.name;
    [cell.tu sd_setImageWithURL:[NSURL URLWithString:m.featureImg]];
    [cell.touxiang sd_setImageWithURL:[NSURL URLWithString:m.avatar]];
    cell.time.text = [LMTTImeChuo compareCurrentTime:m.publishTime];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 165;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    AllModel *m = _dataArr[indexPath.row];
    
    NewsDetailViewController *ndVC = [[NewsDetailViewController alloc] init];
    
    ndVC.str = m.feedId;
    
    [self.navigationController pushViewController:ndVC animated:YES];
    
    [ndVC release];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
